<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="1300" destroy-on-close @closed="$emit('closed')" align-center :close-on-click-modal="false" fullscreen :close-on-press-escape="mode != 'show' ? false : true">
		<el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="120px" label-position="right">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="客户" prop="customer_id">
                        <div style="display:flex;width:100%">
                            <el-input v-model="customer_name" placeholder="请选择客户" @click="checkCustom" readonly></el-input>
                            <el-button type="info" icon="el-icon-Close" @click="clearCustom"></el-button>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="联系人" prop="contacts">
                        <el-select v-model="form.contacts" placeholder="请选择联系人" style="width:100%" clearable filterable>
                            <el-option v-for="item in contactList" :key="item.id" :label="item.contacts" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="开单日期" prop="open_single">
                        <el-date-picker v-model="form.open_single" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="6">
                    <el-form-item label="预付款" prop="advance_price">
                        <el-input v-model="form.advance_price" placeholder="预付款" clearable></el-input>
                    </el-form-item>
                </el-col> -->
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="销售金额" prop="contract_price">
                        <el-input v-model="form.contract_price" placeholder="销售金额" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="销售交期" prop="deliver_date">
                        <el-date-picker v-model="form.deliver_date" type="date" placeholder="请选择交期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="是否含税" prop="is_tax">
                        <el-select v-model="form.is_tax" placeholder="请选择" style="width:100%" clearable>
                            <el-option label="否" :value="0"/>
                            <el-option label="是" :value="1"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="是否开票" prop="is_ticket">
                        <el-select v-model="form.is_ticket" placeholder="请选择" style="width:100%" clearable>
                            <el-option label="否" :value="1"/>
                            <el-option label="是" :value="2"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="核算号" prop="account_num">
                        <el-input v-model="form.account_num" placeholder="核算号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="发货日期" prop="send_date">
                        <el-date-picker v-model="form.send_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="发货物流及单号" prop="send_goods_no">
                        <el-input v-model="form.send_goods_no" placeholder="发货物流及单号" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" placeholder="备注" type="textarea" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="附件" prop="enclosure">
                        <sc-upload-file v-model="form.enclosure" :limit="1">
                            <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
                        </sc-upload-file>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-col :span="24">
                <el-form-item label="产品清单" prop="order_detail">
                    <el-button type="primary" size="small" icon="el-icon-plus" @click="checkGoods">选择商品</el-button>
                    <sc-form-table ref="table" v-model="form.order_detail" :addTemplate="addTemplate" placeholder="暂无数据" height="400">
                        <el-table-column prop="goods_code" label="商品编码" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.goods_code" placeholder="商品编码" :disabled="scope.row.goods_id"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="material_code" label="物料编码" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.material_code" placeholder="物料编码" :disabled="scope.row.goods_id"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="goods_name" label="商品名称" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.goods_name" placeholder="商品名称" :disabled="scope.row.goods_id"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="cate_id" label="分类" align="center">
                            <template #default="scope">
                                <el-cascader :disabled="scope.row.goods_id" v-model="scope.row.cate_id" :options="cateList" :props="cateProps" clearable style="width: 100%;"></el-cascader>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unit_id" label="单位" align="center">
                            <template #default="scope">
                                <el-select :disabled="scope.row.goods_id" v-model="scope.row.unit_id" filterable style="width: 100%" placeholder="请选择单位">
                                    <el-option v-for="item in unitList" :key="item.id" :label="item.unit_name" :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="销售数量" prop="sale_num" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.sale_num" placeholder="销售数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="单价" prop="price" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.price" placeholder="单价" @input="totalCompute" @focus="onFocus($event)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="总价" prop="total_price" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.total_price" placeholder="总价" readonly></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="备注" prop="remark" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="goods_model" label="商品型号" align="center">
                            <template #default="scope">
                                {{scope.row.goods_model}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="goods_spec" label="商品规格" align="center">
                            <template #default="scope">
                                {{scope.row.goods_spec}}
                            </template>
                        </el-table-column>
                        <el-table-column label="单重" prop="weight" align="center">
                            <template #default="scope">
                                {{scope.row.weight}}
                            </template>
                        </el-table-column> -->
                    </sc-form-table>
                </el-form-item>
            </el-col>
            <el-row :gutter="1">
                <el-col :span="8">
                    <el-form-item label="总金额" prop="total_price">
                        <el-input v-model="form.total_price" placeholder="总金额" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="结算账户" prop="settlement_id">
                        <el-select v-model="form.settlement_id" filterable clearable placeholder="请选择账户" style="width:100%">
                            <el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="收款金额" prop="pay_price">
                        <el-input v-model="form.pay_price" placeholder="收款金额" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
		<!-- <template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template> -->
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
            <el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(1)">保存</el-button>
			<el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(2)">保存并审核</el-button>
        </el-footer>
	</el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false"></select-goods>
    <client-list v-if="dialog.client" ref="clientDialog" @success="clientUpdate" @closed="dialog.client=false"></client-list>
</template>

<script>
import ClientList from '../client/list/clientList.vue';
import selectGoods from '../../goods/info/selectGoods.vue';
export default {
    components: { selectGoods, ClientList },
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增销售订单',
				edit: '编辑销售订单',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			//表单数据
			form: {
                id: "",
                customer_id: "",
                contacts: "",
                open_single: this.moment().format('YYYY-MM-DD'),
                advance_price: "",
                contract_price: "",
                deliver_date: "",
                is_tax: "",
                is_ticket: "",
                ship_name: "",
                account_num: "",
                send_date: "",
                send_goods_no: "",
                remark: "",
                enclosure: "",
                status: "",
                order_detail: [],
                total_price: "",
                pay_price: 0,
                settlement_id: "",
			},
			//验证规则
			rules: {
				customer_id: [{ required: true, message: '请选择客户' }],
				contacts: [{ required: true, message: '请选择联系人' }],
			},
            customer_name: "",
            contactList: [],
            unitList: [],
            cateList: [],
            addTemplate:{},
            dialog:{
                goods: false,
                client: false,
            },
            cateProps: {
				value: "id",
				label: "cate_name",
				checkStrictly: true
			},
            accountList: [],
		}
	},
	mounted() {
        this.getCate()  //分类
        this.getUnit() // 单位
        this.getAccount() // 单位
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit(e) {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.contract.contract.edit.post(this.form);
					} else {
						res = await this.$API.contract.contract.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
                        this.visible = false;
                        if(e == 1){
                            this.$emit('success', this.form, this.mode,e)
                            this.$message.success("操作成功")
                        }else{
                            this.$emit('success', res.data, 'check')
                        }
					} else {
						this.$alert(res.message, "提示", { type: 'error' })
					}
				} else {
					return false;
				}
			})
		},
		//表单注入数据
		async setData(data) {
            this.form.id = data.id
            var res = await this.$API.contract.contract.detail.get({id:data.id});
            console.log(res);
            this.form.customer_id = res.data.customer_id
            this.customer_name = data.customer.customer_name
            this.form.open_single = res.data.open_single
            this.form.advance_price = res.data.advance_price
            this.form.contract_price = res.data.contract_price
            this.form.deliver_date = res.data.deliver_date
            this.form.is_tax = res.data.is_tax
            this.form.ship_name = res.data.ship_name
            this.form.account_num = res.data.account_num
            this.form.send_date = res.data.send_date
            this.form.send_date = res.data.send_date
            this.form.send_goods_no = res.data.send_goods_no
            this.form.remark = res.data.remark
            this.form.enclosure = res.data.enclosure
            this.form.status = res.data.status
            this.form.is_ticket = res.data.is_ticket
            this.form.total_price = res.data.total_price
            this.form.pay_price = res.data.pay_price
            this.form.settlement_id = res.data.settlement_id
            this.form.contract_status = res.data.contract_status
            let array = []
            res.data.order_detail.map(item=>{
                array.push({
                    id:item.id,
                    goods_id:item.goods_id,
                    sale_num:item.sale_num,
                    price:item.price,
                    total_price:item.total_price,
                    supplier:item.supplier,
                    standard:item.standard,
                    material:item.material,
                    connect:item.connect,
                    power:item.power,
                    caliber:item.caliber,
                    delivery:item.delivery,
                    remark:item.remark,
                    goods_name:item.goods && item.goods.goods_name,
                    // goods_spec:item.goods && item.goods.goods_spec,
                    // goods_model:item.goods && item.goods.goods_model,
                    unit_name:item.goods && item.goods.unit.unit_name,
                    material_code:item.goods && item.goods.material_code,
                    // weight:item.goods && item.goods.weight,
                    goods_code:item.goods && item.goods.goods_code,

                })
            })
            this.form.order_detail = array
            this.getContact(res.data.customer_id)
            this.form.contacts = res.data.contacts
		},
        onFocus(event){
            event.target.select();
        },
        checkCustom(){
            this.dialog.client = true
            this.$nextTick(() => {
                this.$refs.clientDialog.open('add')
            })
        },
        clientUpdate(data){
            console.log(data);
            this.form.customer_id = data.id
            this.customer_name = data.customer_name
            this.getContact(data.id)
        },
        async getContact(e){
            var res = await this.$API.client.client.detail.get({id:e});
            this.contactList = res.data.customer
        },
        clearCustom(){
            this.form.customer_id = ""
            this.form.contacts = ""
            this.customer_name = ""
            this.contactList = []
        },
        // 选择商品
        checkGoods(e){
            this.dialog.goods = true
            this.$nextTick(() => {
                this.$refs.goodsDialog.open('add').setData(e)
            })
        },
        goodsUpdate(data){
            let array = []
            data.map((item)=>{
                array.push({
                    goods_id:item.id,
                    goods_name:item.goods_name,
                    // goods_spec:item.goods_spec,
                    // goods_model:item.goods_model,
                    unit_name:item.unit.unit_name,
                    cate_id:item.last_cate,
                    unit_id:item.unit_id,
                    material_code:item.material_code,
                    goods_code:item.goods_code,
                    // weight:item.weight,
                    supplier:'自产',
                    sale_num: 1,
                    price:item.factory_price,
                    total_price:item.factory_price,
                })
            })
            let existingIds = this.form.order_detail.map(item => item.goods_id);
            for(let i = array.length - 1; i >= 0; i--){
                if(existingIds.includes(array[i].goods_id)){
                    array.splice(i, 1);
                }
            }
            this.form.order_detail = [...this.form.order_detail,...array]
            this.totalCompute()
        },
        totalCompute() {
            let count_price = 0
            this.form.contract_price = 0
            this.form.total_price = 0
            this.form.order_detail.map(item => {
                if(item.price && item.sale_num){
                    count_price = Number(count_price) + (Number(item.sale_num) * Number(item.price))
                    item.total_price = (Number(item.sale_num) * Number(item.price)).toFixed(2)
                }
            })
            this.form.contract_price = (count_price).toFixed(2)
            this.form.total_price = (count_price).toFixed(2)
		},
        // 获取分类
        async getCate(){
            var res = await this.$API.goods.goodsCate.all.get();
            this.cateList = res.data
        },
        // 获取单位
        async getUnit(){
            var res = await this.$API.goods.goodsUnit.all.get();
            this.unitList = res.data
        },
        // 账户
        async getAccount(){
            var res = await this.$API.finance.account.all.get();
            this.accountList = res.data;
        },
	}
}
</script>

<style></style>
